package com.maixun.lib_network

import android.content.Context
import com.alibaba.sdk.android.oss.ClientConfiguration
import com.alibaba.sdk.android.oss.OSSClient
import com.alibaba.sdk.android.oss.common.auth.OSSFederationToken
import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider
import com.maixun.lib_network.entity.STSResultBeen

/**
 * 作者：Lmoumou
 * 时间：2020/7/14 10:19
 */
class OSSManager {
    companion object {
        private lateinit var mContext: Context

        fun init(mContext: Context) {
            this.mContext = mContext
        }

        @Volatile
        private var instance: OSSManager? = null

        fun getInstance(): OSSManager {
            return instance ?: synchronized(this) {
                instance ?: OSSManager().also { instance = it }
            }
        }
    }

    private val clientMap by lazy { hashMapOf<Int, OSSClient>() }

    fun getOSSClient(stsResultBeen: STSResultBeen, areaTag: Int): OSSClient {
        val ossClient = clientMap[areaTag]
        if (ossClient == null || stsResultBeen.isInvalid()) {
            val accessKeyId = stsResultBeen.accessKeyId
            val accessKeySecret = stsResultBeen.accessKeySecret
            val securityToken = stsResultBeen.securityToken
            val credentialProvider =
                object : OSSStsTokenCredentialProvider(
                    accessKeyId,
                    accessKeySecret,
                    securityToken
                ) {
                    override fun getFederationToken(): OSSFederationToken {
                        return super.getFederationToken()
                    }
                }
            val conf = ClientConfiguration()
            conf.connectionTimeout = 15 * 1000 // 连接超时，默认15秒
            conf.socketTimeout = 15 * 1000 // socket超时，默认15秒
            conf.maxConcurrentRequest = 5 // 最大并发请求数，默认5个
            conf.maxErrorRetry = 2 // 失败后最大重试次数，默认2次
            val client = OSSClient(
                mContext,
                stsResultBeen.endpoint,
                credentialProvider,
                conf
            )
            clientMap[areaTag] = client
            return client
        } else {
            return ossClient
        }
    }


}